<script setup lang="tsx">
import { inject, provide, ref } from 'vue';
import { Button } from 'ant-design-vue';
import { handleTree, parseTime } from '@/utils';
import { delMenu, getMenuTableList } from '@/service/api';
import { useTable, useTableOperate, useTableScroll } from '@/hooks/common/table';
import SvgIcon from '@/components/custom/svg-icon.vue';
import Modal from '@/components/common/modal.vue';
import MenuSearch from './modules/search.vue';
import AddMenuForm, { type OperateType } from './modules/add-menu-form.vue';

const searchParams = ref<MenuPageListApi.MenuTableListParams>({
  menuName: '',
  status: null
});

const { columns, columnChecks, data, loading, pagination, getData } = useTable({
  apiFn: getTableData,
  columns: () => [
    {
      title: '菜单名称',
      align: 'center',
      dataIndex: 'menuName',
      key: 'menuName'
    },
    {
      title: '图标',
      align: 'center',
      dataIndex: 'icon',
      width: '50px',
      key: 'icon',
      customRender: ({ record }) => {
        // 如果是 iconfont 图标
        if (record.iconType === 3 && record.icon) {
          return <i className={`icon iconfont ${record.icon}`} style="font-size: 18px;"></i>;
        }

        // 如果是本地图标（默认类型或明确指定为本地图标）
        if ((record.iconType === 2 || !record.iconType || record.iconType === undefined) && record.icon) {
          // 直接使用 SVG 显示图标，避免使用 SvgIcon 组件可能的默认值问题
          const { VITE_ICON_LOCAL_PREFIX: prefix } = import.meta.env;
          return (
            <div class="flex-center">
              <svg aria-hidden="true" width="18" height="18">
                <use xlinkHref={`#${prefix}-${record.icon}`} fill="currentColor" />
              </svg>
            </div>
          );
        }

        // 如果是 iconify 图标
        if (record.iconType === 1 && record.icon) {
          return (
            <div class="flex-center">
              <SvgIcon icon={record.icon} class="text-icon" style="font-size: 18px;" />
            </div>
          );
        }

        // 如果没有设置图标，显示占位符文本
        if (!record.icon) {
          return (
            <div class="flex-center" style="font-size: 12px; color: #999;">
              无图标
            </div>
          );
        }

        // 其他情况显示未知
        return (
          <div class="flex-center" style="font-size: 12px; color: #999;">
            未知
          </div>
        );
      }
    },
    {
      title: '菜单类型',
      align: 'center',
      dataIndex: 'menuType',
      width: '100px',
      key: 'menuType',
      customRender: ({ record }) => {
        const menuTypeObj: any = {
          M: {
            text: '目录',
            color: '#646cff'
          },
          C: {
            text: '菜单',
            color: '#52C14A'
          },
          F: {
            text: '按钮',
            color: '#1890ff'
          },
          A: {
            text: 'APP目录',
            color: '#5F4FD9'
          }
        };

        return (
          <span
            style={{
              color: menuTypeObj[record.menuType].color
            }}
          >
            {menuTypeObj[record.menuType].text}
          </span>
        );
      }
    },
    {
      title: '排序',
      align: 'center',
      dataIndex: 'orderNum',
      width: '50px',
      key: 'orderNum'
    },
    {
      title: '权限标识',
      align: 'center',
      dataIndex: 'perms',
      key: 'perms'
    },
    {
      title: '路径',
      align: 'center',
      dataIndex: 'path',
      key: 'path'
    },
    {
      title: '状态',
      align: 'center',
      dataIndex: 'status',
      key: 'status',
      customRender: ({ record }) => {
        const status = ['success', 'error'];
        return (
          <span style={{ color: `rgb(var(--${status[record.status]}-color))` }}>
            {record.status === '0' ? '正常' : '停用'}
          </span>
        );
      }
    },
    {
      title: '创建时间',
      align: 'center',
      dataIndex: 'createTime',
      key: 'createTime',
      customRender: ({ record }) => {
        return <div>{parseTime(record.createTime)}</div>;
      }
    },
    {
      key: 'operate',
      title: '操作',
      align: 'center',
      width: 200,
      customRender: ({ record }) => (
        <div class="flex-center gap-8px">
          <Button type="primary" ghost size="small" onClick={() => add('addChild', record)}>
            新增子菜单
          </Button>
          <Button type="primary" ghost size="small" onClick={() => add('edit', record)}>
            修改
          </Button>
          <Button danger size="small" onClick={() => handleDelete(record.menuId)}>
            删除
          </Button>
        </div>
      )
    }
  ]
});
const { checkedRowKeys, rowSelection } = useTableOperate(data, getData);
const { tableWrapperRef, scrollConfig } = useTableScroll();

provide('query', () => {
  getData();
});
function reset(val: MenuPageListApi.MenuTableListParams) {
  getData();
}
function search(val: MenuPageListApi.MenuTableListParams) {
  getData();
}

const addVisible = ref(false);
const operateType = ref<OperateType>('add');
const operateTypeText: Record<OperateType, string> = {
  add: '新增菜单',
  edit: '修改菜单',
  addChild: '新增子菜单'
};
const currentRow = ref<any>(null);
function add(type: 'add' | 'edit' | 'addChild', row: any = null) {
  console.log('row :>> ', row);
  currentRow.value = { queryList: [], ...row };
  if (type == 'addChild') {
    const obj = {
      parentId: row.menuId,
      menuType: 'M',
      menuName: '',
      iconType: '1',
      icon: null,
      orderNum: null,
      layout: null,
      routePath: null,
      routeName: null,
      page: null,
      status: '0',
      hideInMenu: false,
      perms: null,
      constant: false,
      href: '',
      queryList: [],
      component: null,
      pathParam: '',
      query: '',
      visible: '1',
      isCache: '1'
    };
    currentRow.value = obj;
  }
  operateType.value = type;
  addVisible.value = true;
}

const menuListData = ref([]);

function getTableData() {
  return new Promise<any>((resolve, reject) => {
    getMenuTableList(searchParams.value)
      .then(({ data, error }) => {
        if (!error) {
          const mapData = data
            ?.map(item => {
              return {
                label: item.menuName,
                key: item.menuId,
                value: item.menuId,
                ...item
              };
            })
            .filter(item => item.menuType != 'F');
          menuListData.value = handleTree(mapData, 'menuId');
          const list = handleTree(data, 'menuId');
          console.log('list :>> ', list);
          resolve({
            error,
            data: {
              list
            }
          });
        } else {
          resolve({
            error,
            data: []
          });
        }
      })
      .catch(error => {
        reject(error);
      });
  });
}

function handleDelete(id: number) {
  window.$modal?.confirm({
    title: `确定删除菜单id为${id}的菜单吗?`,
    onOk() {
      delMenu(id).then(({ data, error }) => {
        if (!error) {
          window.$message?.success('删除成功');
          getData();
        }
      });
    },
    onCancel() {}
  });
}

const addMenuFormRef = ref(null);
function handleResetAddForm() {
  addMenuFormRef.value.resetForm();
}

function handleAddFormClose(val) {
  if (val) {
    addMenuFormRef.value.resetForm();
  }
}

function handleAddFormOk() {
  addMenuFormRef.value.handleSubmit();
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <MenuSearch v-model:model="searchParams" @reset="reset" @search="search" />
    <ACard
      :bordered="false"
      :body-style="{ flex: 1, overflow: 'hidden' }"
      class="table-card flex-col-stretch sm:flex-1-hidden card-wrapper"
    >
      <template #title>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="add('add')">
          <template #icon>
            <icon-ic-round-add class="align-sub text-icon" />
          </template>
          <span class="ml-3px">新增</span>
        </AButton>
      </template>
      <template #extra>
        <TableColumnSetting v-model:columns="columnChecks" />
      </template>
      <ATable
        ref="tableWrapperRef"
        :columns="columns"
        :data-source="data"
        size="small"
        :loading="loading"
        row-key="menuId"
        :scroll="scrollConfig"
        :pagination="false"
        class="h-full"
      />
    </ACard>

    <Modal
      v-model:visible="addVisible"
      :title="operateTypeText[operateType]"
      height="70vh"
      width="1000px"
      :destroy-on-close="true"
      @reset="handleResetAddForm"
      @ok="handleAddFormOk"
      @close="handleAddFormClose"
    >
      <AddMenuForm ref="addMenuFormRef" :operate-type="operateType" :menu-list="menuListData" :row-data="currentRow" />
    </Modal>
  </div>
</template>

<style></style>
